<template>
	<view class="content">
		<navbar :title="title" :isback="isback"></navbar>
		<view
			style="width: 100%;position: absolute;top: 30rpx;z-index: 10;display: flex;align-items: center;justify-content: center;">
			<u-loading mode="circle" color="green" size="50"></u-loading>
		</view>

		<view class="myself" @click="toUserInfo" v-if="userInfo.uid">
			<u-icon name="account-fill" style="margin-right: 10rpx;" color="#2979ff" size="28"></u-icon>
			<text>个人中心</text>
		</view>
		
		<view class="myself" style="top: 280rpx;" @click="toNewsDetail()" v-if="unread == 0 && is_create && userInfo.uid">
			<text>消息通知</text>
		</view>


		<!-- <view style="height: 78rpx;background: #FFFFFF;" v-else></view> -->

		<view class="tourist" style="justify-content: flex-start;" v-if="unread > 0 && is_create" @click="toNewsDetail()">
			您有<text style="color: red;">{{unread}}</text>条未读消息
		</view>
		
		<view class="tourist" @click="toLogin" v-if="!userInfo.uid">
			<text>您当前为游客身份</text>
			<text>去登录</text>
		</view>

		<!-- 列表 -->
		<view class="new_list" v-for="(item,index) in list" :key="index">
			<view class="list_title" @click="toDetail(item._id)">
				{{item.title}}
			</view>
			<view class="list_info" @click="toDetail(item._id)">
				<u-button @click.stop="viewImg([item.avatar],item.avatar)" :custom-style="avatar">
					<u-image width="60rpx" height="60rpx" shape="circle" :src="item.avatar"></u-image>

				</u-button>
				<text style="margin-left: 20rpx;">{{item.name}}</text>
			</view>
			<u-read-more ref="uReadMore" :color="$store.state.color" text-indent="0">
				<view class="list_content" @click="toDetail(item._id)">
					{{item.content}}
				</view>
			</u-read-more>

			<image :src="item.filthImg[0]" v-if="item.filthImg.length == 1" mode="aspectFit"
				style="margin-top: 20rpx;width: 320rpx;" @click="viewImg(item.filthImg,item.filthImg[0])"></image>
			<view class="list_img" v-else>
				<view class="img" v-for="(it,idx) in item.filthImg" :key="it">
					<u-image width="100%" height="100%" :src="it" @click="viewImg(item.filthImg,it)"></u-image>
				</view>
			</view>

			<view class="list_createTime">
				<view>
					{{$u.timeFrom(item.createTime, 'yyyy年mm月dd日')}}
				</view>
				<view class="hudong" v-if="is_create">
					<u-icon :name="item.is_zan==1?'heart-fill':'heart'" :color="item.is_zan==1?'red':''" size="50"
						@click="zan(item,index)"></u-icon>

					<u-icon name="chat" size="50" style="margin-left: 20rpx;" @click="lun({uid:'',name: ''},index)"></u-icon>

				</view>
			</view>
			<view class="zan_list" v-if="item.zan.length > 0">
				<text v-for="(it,idx) in item.zan" :key="it.name">{{it.name}} 、</text>
			</view>
			<view class="zan_list comment" v-if="item.comment.length > 0">
				<view class="comment_list" v-for="(comment,idxx) in item.comment" :key="idxx+'comment'">
					<text @click="lun({uid:comment.uid,name: comment.name},index)">{{comment.name}}</text>
					<view class="passive" v-if="comment.passive_uid">
						<text style="color: #000000;">回复</text>
						<text @click="lun({uid:comment.passive_uid,name: comment.passive_name},index)">{{comment.passive_name}}</text>
					</view>
					<text style="color: #000000;"> ：</text>
					
					<text style="color: #000000;">{{comment.content}}</text>
				</view>
			</view>

			<!-- <button type="default" @click="remove(item._id,index)">删除</button> -->
		</view>
		<!-- 评论 -->
		<view class="pinglun" v-if="is_pinglun">
			<view @click="is_pinglun=false"></view>
			<view>
				<u-input v-model="value" :placeholder="passive.name?'回复'+passive.name+'：':'评论'" :focus="focusInput" :type="type" style="width: 100%;background-color: #FFFFFF;padding: 0 10rpx;" />
				<u-button shape="circle" @click="lunSend()" :custom-style="{width: '200rpx',color:'#000000 !important',background: $store.state.color}">评论</u-button>
				<!-- <button type="default">发送</button> -->
			</view>
			
		</view>

		<u-empty mode="message" text="快去发言吧~" :show="isShowEmpty"></u-empty>


		<u-back-top :scroll-top="scrollTop"
			:custom-style="{width:'100rpx',height:'100rpx',backgroundColor: $store.state.color}"></u-back-top>
		<u-popup v-model="show" mode="top">
			<scroll-view scroll-y="true">
				<view class="create">
					<navbar :title="title" :isback="isback"></navbar>
					<u-input type="text"
						style="width: 100%;background-color: #f8f5f0;padding: 0 10rpx;box-sizing: border-box;"
						placeholder="发言标题" v-model="form.title" />
					<view class="textarea">
						<textarea placeholder="发言内容" maxlength="-1" v-model="form.content" />
						<text>{{form.content.length}}字</text>
					</view>
					<view class="upImg">
						<view class="upImg_list" v-for="(item,index) in filthImg" :key="index">
							<u-icon name="trash" size="40" style="position: absolute;top: 4rpx;right: 2rpx;z-index: 2;"
								@click="removeTrash(index)"></u-icon>
							<u-image width="120rpx" height="120rpx" :src="item" @click="viewImg(filthImg,item)">
							</u-image>
						</view>
						<view class="upImg_list" @click="upImg()" v-if="filthImg.length < 9">
							<u-icon name="photo" color="#8a8a8a" size="48"></u-icon>
						</view>
					</view>
					<view class="" style="margin: 100rpx 0 50rpx;">

						<u-button shape="circle" @click="up()"
							:custom-style="{width: '500rpx',color:'#000000',background: $store.state.color}">记录
						</u-button>
					</view>
				</view>
			</scroll-view>

		</u-popup>
		<u-icon name="plus-circle-fill" color="#F0AD4E" size="150" class="plusMemory" @click="show = true"
			v-if="is_create"></u-icon>
			
		<u-no-network></u-no-network>
	</view>
</template>

<script>
	// import creatMemory from '../../components/creatMemory.vue'
	export default {
		// comments:{creatMemory},
		data() {
			return {
				title: '广场',
				isback: true,
				// 发表评论
				value: '',
				type: 'text',
				focusInput: true, // 是否聚焦
				listIndex: 0, // 评论第几条笔记
				passive: {},  // 被回复人的信息
				is_pinglun: false, // 是否显示评论输入框
				
				unread: 0, // 未读消息通知数

				avatar: {
					width: '60rpx',
					height: '60rpx',
					borderRadius: '50%',
					margin: '0',
					border: '1rpx solid #ffffff'
				},

				form: {
					title: '',
					content: '',
				},
				filthImg: [],
				list: [],
				is_create: false, // 审核时禁止用户自定义内容
				isShowEmpty: false, // 是否显示内容为空组件
				userInfo: {}, // 用户信息
				show: false, // 发表记录的弹窗
				pageIndex: 1, // 第几页
				hasMore: true, // 是否还有更多默认true
				is_pull: false, // 是否刷新状态

				scrollTop: 0, // 返回顶部
			}
		},
		onLoad(options) {
			this.get();
			if (options._id) {
				this.toDetail(options._id);
			}
		},
		onShow() {
			this.userInfo = uni.getStorageSync("userInfo");
			this.getNotic();
		},
		methods: {
			// 点赞
			zan(item, index) {
				if (!this.userInfo.uid) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '../miniLogin/miniLogin'
						})
					}, 1200)
					return
				}
				let that = this;
				uni.showLoading({
					title: '点赞中...'
				})
				uniCloud.callFunction({
					name: 'add',
					data: {
						_id: item._id, // 标识本条数据的id
						memor_uid: item.uid, // 本条内容的发布者id
						zan: {
							uid: that.$store.state.uid,
							name: that.userInfo.name,
							createTime: Date.now(), // 创建时间
						},
						zan_status: item.is_zan == 1 ? 2 : 1, // 1:点赞。2:取消点赞
						type: 'zan'
					}
				}).then((res) => {
					uni.hideLoading();
					// console.log(res);
					that.list[index].is_zan = item.is_zan == 1 ? 2 : 1
					that.list[index].zan = res.result.data[0].zan
					uni.showToast({
						title: res.result.msg,
						icon: 'none'
					})

				}).catch((err) => {
					uni.hideLoading()
					uni.showModal({
						content: err,
						showCancel: false
					})
				})
			},
			// 评论
			lun(item,index) {
				this.listIndex = index;
				// console.log(item);
				this.passive = item;
				this.is_pinglun = true;
			},
			// 发送评论
			lunSend(){
				if(this.value == ''){
					uni.showToast({
						title: '请输入您的评论',
						icon: 'none'
					})
					return
				}
				if (!this.userInfo.uid) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '../miniLogin/miniLogin'
						})
					}, 1200)
					return
				}
				let that = this;
				uni.showLoading({
					title: '评论中...'
				})
				uniCloud.callFunction({
					name: 'add',
					data: {
						_id: that.list[that.listIndex]._id, 
						memor_uid: that.list[that.listIndex].uid, // 本条内容的发布者id
						comment: {
							uid: that.$store.state.uid,
							name: that.userInfo.name,
							passive_uid: that.passive.uid,
							passive_name: that.passive.name,
							content: that.value,
							createTime: Date.now(), // 创建时间
						},
						type: 'lun'
					}
				}).then((res) => {
					uni.hideLoading();
					// console.log(res);
					that.list[that.listIndex].comment = res.result.data[0].comment;
					// 评论成功之后清空脏数据
					that.value = '';
					that.passive = {};
					// 评论成功之后隐藏评论输入框
					that.is_pinglun = false;
					
					uni.showToast({
						title: res.result.msg,
						icon: 'none'
					})
				
				}).catch((err) => {
					uni.hideLoading()
					uni.showModal({
						content: err,
						showCancel: false
					})
				})
			},
			// 查看详情
			toDetail(_id) {
				uni.navigateTo({
					url: 'memorDetail/memorDetail?_id=' + _id
				})
			},
			// 预览图片
			viewImg(urls, current) {
				this.common.viewImg(urls, current)
			},
			// 发布记录的图片
			async upImg() {
				let img = await this.common.indexImg(9 - this.filthImg.length);
				this.filthImg = this.filthImg.concat(img);
			},
			// 删除要发布的图片
			removeTrash(index) {
				this.filthImg.splice(index, 1)
			},

			async add(filthImg) {
				var that = this;

				uni.showLoading({
					title: '发布中...'
				})
				let num = this.$u.random(0, 1997); // 游客身份随机数
				let avatar =
					'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-6e1a92c2-19ad-4ad9-ba4a-caf65b14a00b/6ab34ddf-0941-4b8b-bbdf-cf6a53929eb6.jpg'; // 游客身份头像
				uniCloud.callFunction({
					name: 'add',
					data: {
						uid: that.$store.state.uid, // 添加uid，表示用户标识
						createTime: Date.now(), // 创建时间
						name: that.userInfo.name ? that.userInfo.name : '一团团' + num,
						avatar: that.userInfo.avatar ? that.userInfo.avatar : avatar,
						title: that.form.title,
						content: that.form.content,
						filthImg: filthImg,
						zan: [],
					}
				}).then((res) => {
					uni.hideLoading()
					uni.showToast({
						title: '发布成功'
					})
					that.show = false; // 发布成功后隐藏弹窗
					// 发布成功后清空旧数据
					that.form.title = '';
					that.form.content = '';
					that.filthImg = [];

					// return res.result.id
				}).catch((err) => {
					uni.hideLoading()
					uni.showModal({
						content: `添加数据失败，错误信息为：${err.message}`,
						showCancel: false
					})
					console.error(err)
				})
			},
			// 点击记录按钮之后先上传图片再请求记录接口
			up() {
				// 用户发布之后再上传图片
				if (this.form.title == '' || this.form.content == '') {
					uni.showToast({
						title: '请输入您的记录',
						icon: 'none'
					})
					return
				}
				if (this.filthImg.length == 0) {
					this.add([]);
					return
				}
				let filthImg = [];
				uni.showLoading({
					title: '上传图片中...'
				})
				for (let i = 0; i < this.filthImg.length; i++) {
					const result = uniCloud.uploadFile({
						filePath: this.filthImg[i],
						cloudPath: String(Math.random() * 5).split('.')[1] + '.png',
					})
					result.then(res => {
						uni.hideLoading();
						console.log(res);
						//获取到上传到云储存的url地址 
						// console.log(res['fileID']);
						filthImg.push(res['fileID'])
						if (this.filthImg.length == filthImg.length) {
							this.add(filthImg);
						}
					})
					result.catch(err => {
						uni.showToast({
							title: '图片处理失败，请稍后再次发布',
							icon: 'none'
						})
						return
					})
				}
				// console.log(filthImg);
			},


			// 获取数据
			get() {
				let that = this;
				uni.showLoading({
					title: '获取中...'
				})
				uniCloud.callFunction({
					name: 'get',
					data: {
						dbName: 'memor-pool', //要查询的表名
						filter: {}, //筛选条件，格式{sex:'女'}
						pageIndex: this.pageIndex, //第几页
						pageSize: 10 //每页的记录条数
					},
					success(res) {
						uni.hideLoading();
						if (that.is_pull) {
							// this.pageIndex = 1;
							that.list = [];
						}
						// console.log(res);
						//停止下拉样式
						uni.stopPullDownRefresh();
						that.is_pull = false;
						let datalist = res.result.data;
						// 判断是否已点赞
						datalist.forEach((item, index) => {
							item.is_zan = 2;
							if (item.zan) {
								item.zan.forEach((it, idx) => {
									if (it.uid == that.$store.state.uid) {
										item.is_zan = 1;
										return
									}
								})
							}

						})
						that.list = that.list.concat(datalist);
						if (that.list.length == 0) { // 不知为何小程序页面内直接判断实效，后面找原因
							that.isShowEmpty = true
						} else {
							that.isShowEmpty = false
						}
						that.hasMore = res.result.hasMore; // 是否还有更多
						that.is_create = res.result.is_create; // 是否可自定义内容
					}
				})
			},
			// 获取未读通知
			getNotic(){
				let that = this;
				uniCloud.callFunction({
					name: 'notic',
					data: {
						index: 0, // 表示首页
						filter: {
							memor_uid: that.$store.state.uid, // 添加uid，表示用户标识
							is_read: 2,  // 1已读 2未读
						}, //筛选条件，格式{sex:'女'}
						
					}
				}).then((res) => {
					// console.log(res);
					that.unread = res.result.data;
					
				}).catch((err) => {
					uni.showModal({
						content: `获取失败，错误信息为：${err.message}`,
						showCancel: false
					})
					
				})
			},
			// 个人中心
			toUserInfo() {
				uni.navigateTo({
					url: '../me/me'
				})
			},
			// 去登录
			toLogin() {
				uni.navigateTo({
					url: '../miniLogin/miniLogin'
				})
			},
			// 返回顶部
			onPageScroll(e) {
				this.scrollTop = e.scrollTop;
			},
			// 跳转消息通知列表
			toNewsDetail(){
				uni.navigateTo({
					url: '../notic/notic'
				})
			},
		},
		onShareAppMessage(res) {
			let userInfo = uni.getStorageSync("userInfo");
			let title = (userInfo ? userInfo.name : '一团团') + '邀请您分享日记';
			return {
				title: title,
				path: 'pages/index/index',
				imageUrl: '../../static/share_image.jpg',
				desc: '',
				content: ''
			}
		},

		// 下拉的生命周期
		onPullDownRefresh() {
			this.pageIndex = 1;
			// this.list = [];
			this.is_pull = true;
			this.get();
			this.getNotic();

		},
		// 上拉
		onReachBottom() {
			if (this.hasMore) {
				this.pageIndex++
				this.get();
			} else {
				// uni.showToast({
				// 	title: '没有更多数据了！',
				// 	icon: 'none'
				// })
			}
		},
	}
</script>

<style scoped>
	.content {
		background-color: #EDEDED;
	}

	.new_list {
		margin-bottom: 10rpx;
		padding: 30rpx;
		background-color: #FFFFFF;
	}

	.list_title {
		font-weight: bold;
		font-size: 34rpx;
	}

	.list_info {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		color: #999999;
		font-size: 24rpx;
	}

	.list_content {
		font-size: 28rpx;
	}

	.list_img {
		width: 80%;
		display: flex;
		flex-wrap: wrap;
	}

	.img {
		width: 150rpx;
		height: 150rpx;
		border-radius: 6rpx;
		margin: 10rpx 10rpx 0 0;
	}

	.list_createTime {
		font-size: 24rpx;
		display: flex;
		/* justify-content: flex-end; */
		justify-content: space-between;
		margin-top: 30rpx;
		color: #999999;
	}

	.hudong {
		display: flex;
		align-items: center;
	}

	.zan_list {
		background-color: #f7f7f7;
		padding: 10rpx 20rpx;
		margin-top: 10rpx;
		color: #566a94;
		display: flex;
		flex-wrap: wrap;
		border-radius: 4rpx;
	}
	
	.comment{
		display: flex;
		flex-direction: column;
	}
	.comment_list{
		display: flex;
		padding: 10rpx 0;
		border-bottom: 1rpx solid #e0e0e0;
		font-size: 26rpx;
	}
	.comment_list:last-child{
		border: none;
	}
	.comment_list>text{
		
	}


	.myself {
		position: fixed;
		right: 0;
		top: 380rpx;
		border-radius: 50rpx 0 0 50rpx;
		background-color: #F0AD4E;
		z-index: 99;
		padding: 10rpx 20rpx;
		display: flex;
		align-items: center;
	}

	.tourist {
		/* position: fixed; */
		top: 0;
		width: 100%;
		background-color: #F0AD4E;
		padding: 10rpx 30rpx;
		display: flex;
		justify-content: space-between;
		z-index: 99;
		font-size: 28rpx;
	}

	.plusMemory {
		position: fixed;
		bottom: 50rpx;
		left: 50%;
		margin-left: -75rpx;
	}

	.create {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx;
		max-height: 80vh;
	}


	.textarea {
		width: 100%;
		/* position: relative; */
		margin: 20rpx 0;
		background-color: #f8f5f0;
		border-radius: 6rpx;

		/* box-sizing: border-box; */
	}

	.textarea textarea {
		width: 100%;
		padding: 10rpx;
	}

	.textarea text {
		/* position: absolute;
		bottom: -40rpx;
		right: 10rpx; */
		display: block;
		color: #d2d2d2;
		font-size: 26rpx;
		width: 100%;
		background-color: #f8f5f0;
		text-align: right;
		padding: 10rpx;
	}

	.upImg {
		width: 100%;
		display: flex;
		flex-wrap: wrap;

	}

	.upImg_list {
		width: 120rpx;
		height: 120rpx;
		border: 1rpx solid #eeeeee;
		border-radius: 18rpx;
		text-align: center;
		line-height: 150rpx;
		margin-right: 20rpx;
		margin-top: 20rpx;
		position: relative;
	}

	/deep/.u-empty {
		background-color: #FFFFFF;
	}

	/deep/.u-btn {
		padding: 0 !important;
	}

	/deep/.u-btn--default {
		color: #FFFFFF !important;
	}
	
	/* 发表评论 */
	.pinglun{
		position: fixed;
		top: 0;
		width: 100%;
		height: 100vh;
		background-color: rgba(0,0,0,0);
		z-index: 9999;
	}
	.pinglun>view:first-child{
		width: 100%;
		height: 100%;
	}
	.pinglun>view:nth-child(2){
		position: absolute;
		bottom: 0;
		z-index: 9999999;
		background-color: #fafbfb;
		width: 100%;
		display: flex;
		align-items: center;
		padding: 10rpx 20rpx;
	}
</style>
